from infos import constants, db
from infos.models import Category, News, User
from infos.modules.user import user_blu
from infos.utils.commons import login_in
from flask import render_template, g, redirect, request, jsonify, current_app
from infos.utils.response_code import RET
from infos.utils.storage import storage


# 文章
@user_blu.route('/other_news_list')
@login_in
def other_news_list():
    # 取参数
    other_id = request.args.get('user_id')
    page = request.args.get('p', 1)

    # 判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')

    if not other:
        return jsonify(errno=RET.NODATA, errmsg='当前用户不存在')

    try:
        paginate = other.news_list.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')

    news_dict_li = []
    for news_item in news_li:
        news_dict_li.append(news_item.to_basic_dict())

    data = {
        'news_list': news_dict_li,
        'total_page': total_page,
        'current_page': current_page
    }
    return jsonify(errno=RET.OK, errmsg='OK', data=data)


# 新闻作者
@user_blu.route('/other_dic')
@login_in
def other_dic():
    user = g.user
    page = request.args.get('page_id', 1)

    try:
        user_id = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        others = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')

    is_followed = False
    # 判断当前新闻有作者,并且当前登录用户已关注过这个用户
    if others and user:
        # if user 是否关注过 news.user
        if others in user.followed:
            is_followed = True

    data = {
        'other_info': others.to_dict(),
        'user': g.user.to_dict() if g.user else None,
        'is_followed': is_followed
    }

    return render_template('user/other.html', data=data)


# 关注
@user_blu.route('/user_followed')
@login_in
def user_followed():
    user = g.user
    page = request.args.get('page_id', 1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 分页
    paginate = user.followed.paginate(page, 6, False)
    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    user_list = []
    for other in items:
        user_list.append(other.to_dict())

    data = {
        'current_page': current_page,
        'total_page': total_page,
        'items': items,
        'users': user_list
    }

    return render_template('user/user_follow.html', data=data)


# 审核新闻
@user_blu.route('/user_news_list')
@login_in
def user_news_list():
    user = g.user
    page = request.args.get('page_id', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 分页
    paginate = user.news_list.paginate(page, 6, False)
    total_page = paginate.pages
    current_page = paginate.page
    news_list = paginate.items

    news_dic_list = []
    for news in news_list:
        news_dic_list.append(news.to_review_dict())
    data = {
        'news_dic_list': news_dic_list,
        'total_page': total_page,
        'current_page': current_page
    }
    return render_template('user/user_news_list.html', data=data)


# 新闻发布
@user_blu.route('/user_release', methods=['GET', 'POST'])
@login_in
def user_release():
    user = g.user
    if request.method == 'GET':
        try:
            categorys = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
        category_list = []
        for category in categorys:
            category_list.append(category.to_dict())
        category_list.pop(0)
        data = {
            'category_list': category_list
        }
        return render_template('user/user_news_release.html', data=data)

    # 1. 获取要提交的数据
    # 标题
    title = request.form.get("title")
    # 新闻来源
    source = "个人发布"
    # 摘要
    digest = request.form.get("digest")
    # 新闻内容
    content = request.form.get("content")
    # 索引图片
    index_image = request.files.get("index_image")
    # 分类id
    category_id = request.form.get("category_id")

    if all in ([title, digest, content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    try:
        key = storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据库错误')

    return jsonify(errno=RET.OK, errmsg='成功')


# 收藏新闻
@user_blu.route('/user_collect')
@login_in
def user_collect():
    user = g.user
    page = request.args.get('page_id', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='数据错误')

    # 分页
    paginate = user.collection_news.paginate(page, 6, False)

    current_page = paginate.page
    total_page = paginate.pages
    news_list = paginate.items

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    data = {
        'current_page': current_page,
        'total_page': total_page,
        'news_dict_list': news_dict_list
    }
    return render_template('user/user_collection.html', data=data)


# 修改密码
@user_blu.route('/pass_info', methods=['POST', 'GET'])
@login_in
def pass_info():
    user = g.user
    if request.method == 'GET':
        return render_template('user/user_pass_info.html')

    new_password = request.json.get('new_password')
    old_password = request.json.get('old_password')
    new_password2 = request.json.get('new_password2')

    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg='密码错误')
    if all in ([new_password, new_password2]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if new_password != new_password2:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    user.password = new_password
    return jsonify(errno=RET.OK, errmsg='成功')


# 上传头像
@user_blu.route('/pic_info', methods=['POST', 'GET'])
@login_in
def pic_info():
    user = g.user
    if request.method == 'GET':
        return render_template('user/user_pic_info.html', data={})
    avatar = request.files.get('avatar').read()

    if not avatar:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        key = storage(avatar)
    except Exception as e:
        raise e
    user.avatar_url = key

    return jsonify(errno=RET.OK, errmsg='成功', data={'avatar_url': constants.QINIU_DOMIN_PREFIX + key})


# 修改用户信息
@user_blu.route('/base_info', methods=['POST', 'GET'])
@login_in
def user_base_info():
    user = g.user
    if request.method == 'POST':
        # 拿到ajax中的参数
        signature = request.json.get('signature')
        nick_name = request.json.get('nick_name')
        gender = request.json.get('gender')

        # 判断是否拿到参数
        if all in ([signature, nick_name, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
        # 判断性别
        if gender not in ('MAN', 'WOMEN'):
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

        # 改数据
        user.signature = signature
        user.nick_name = nick_name
        user.gender = gender

        return jsonify(errno=RET.OK, errmsg='成功')
    else:
        date = {
            'user': user.to_dict() if user else None
        }
        return render_template('user/user_base_info.html', data=date)


@user_blu.route('/info')
@login_in
def user_in():
    user = g.user
    if not user:
        return redirect('/info')
    data = {
        'user': user.to_dict() if user else None
    }
    return render_template('user/user.html', data=data)
